package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gin-wheel/app/routers"
	_ "gin-wheel/cmd/init"
	"gin-wheel/global"
)

func main() {
	router := routers.NewRouter()
	s := &http.Server{
		Addr:           global.ServerSetting.Port,
		Handler:        router,
		ReadTimeout:    global.ServerSetting.ReadTimeout * time.Second,
		WriteTimeout:   global.ServerSetting.WriteTimeout * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	// 优雅重启
	go func() {
		if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			info := fmt.Sprintf("s.ListenAndServe err: %v", err)
			global.ZapLog.Error(info)
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	global.ZapLog.Info("Shuting down server...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := s.Shutdown(ctx); err != nil {
		info := fmt.Sprintf("Server forced to shutdown: %v", err)
		global.ZapLog.Error(info)
	}

	global.ZapLog.Info("Server exiting")
}
